package com.yuanfeng.userms.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.shop.ShopIndexVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.userms.entity.UserFavoritesShopEntity;
import com.yuanfeng.userms.feign.BusinessServiceClient;
import com.yuanfeng.userms.feign.GoodsServiceClient;
import com.yuanfeng.userms.mapper.UserFavoritesShopMapper;
import com.yuanfeng.userms.service.UserFavoritesShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserFavoritesShopServiceImpl
 * @Description 收藏的店铺
 * @Author cyp
 * @Date 2023-05-26 16:35:37
 * @Version 1.0
 **/
@Service
public class UserFavoritesShopServiceImpl extends ServiceImpl<UserFavoritesShopMapper, UserFavoritesShopEntity>
        implements UserFavoritesShopService {
    @Autowired
    private BusinessServiceClient businessServiceClient;

    @Autowired
    private GoodsServiceClient goodsServiceClient;

    @Override
    public ResponseResult check(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        paraMap.put("userId", userInfo.getUserId());
        String torf = this.baseMapper.checkFavoriteShopOrNot(paraMap);
        if (null != torf) {
            return ResponseResult.success("已收藏", 1);
        }
        return ResponseResult.success("未收藏", 0);
    }

    @Override
    public ResponseResult add(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        paraMap.put("userId", userInfo.getUserId());

        String favoritesShopId = this.baseMapper.checkFavoriteShopOrNot(paraMap);
        if (null != favoritesShopId) {
            Integer integer = this.baseMapper.deleteFavoriteShopOrNot(paraMap);
            paraMap.put("type", "2");
            ResponseResult resultResp = businessServiceClient.updateShopCollect(paraMap);
            if (1 == integer && resultResp.getCode() == 1) {
                return ResponseResult.success("删除收藏的店铺");
            }
            return ResponseResult.fail(0, "删除收藏的店铺失败");
        }
        Integer torf = this.baseMapper.addFavoriteShop(paraMap);
        paraMap.put("type", "1");
        ResponseResult resultResp = businessServiceClient.updateShopCollect(paraMap);
        if (1 == torf && resultResp.getCode() == 1) {
            return ResponseResult.success("增加收藏的店铺");
        }
        return ResponseResult.fail(0, "增加收藏的店铺失败");
    }

    @Override
    public ResponseResult get(Map<String, Object> paraMap) {
        try {
            String token = (String) paraMap.get("token");
            String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);
            paraMap.put("userId", userId);
            Map<String, Object> resultMap = new HashMap<>();
            if (null == paraMap.get("page") && null == paraMap.get("limit")) {
                return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
            }
            //将对象转换为map
            Map data = ParseMapUtils.beanToMap(paraMap);

            //分页查询数据
            IPage<UserFavoritesShopEntity> page = this.baseMapper.selectPage(new Query<UserFavoritesShopEntity>().getPage(data), new LambdaQueryWrapper<UserFavoritesShopEntity>()
                    .eq(UserFavoritesShopEntity::getUserId, userId)
                    .groupBy(UserFavoritesShopEntity::getShopId)
                    .orderByDesc(UserFavoritesShopEntity::getFavoritesShopTime));


            //查询是否有数据
            if (CollectionUtils.isEmpty(page.getRecords())) {
                return ResponseResult.fail(BizCodeEnume.COLLECTION_IS_EMPTY);
            }
            List<ShopIndexVO> results = new ArrayList<ShopIndexVO>();
            for (UserFavoritesShopEntity userFavoriteShop : page.getRecords()) {
                HashMap<String, String> selectMap = new HashMap<String, String>();
                selectMap.put("orderType", "2");
                selectMap.put("currentPage", "1");
                selectMap.put("pageSize", "5");
                selectMap.put("shopId", userFavoriteShop.getShopId().toString());

                ResponseResult resultResp = goodsServiceClient.getDetailByShopId(selectMap);
                if (null != resultResp.getData()) {
                    ShopIndexVO shopIndexQueryResult = JSON.parseObject(JSON.toJSONString(resultResp.getData()), ShopIndexVO.class);

                    results.add(shopIndexQueryResult);
                }
            }
            IPage<ShopIndexVO> resultPage=new Page<>();
            resultPage.setTotal(page.getTotal());
            resultPage.setRecords(results);
            resultPage.setPages(page.getPages());
            return ResponseResult.success(BizCodeEnume.SUCCESSFULLY_QUERIED_FAVORITE_STORES.getMsg(), PageUtils.getPage(resultPage));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult delete(Map<String, Object> paraMap) {
        String token = (String) paraMap.get("token");
        String userId = RedisUtil.get(YFConfig.YF_USER_TOKEN_USERID + token);
        paraMap.put("userId", userId);

        @SuppressWarnings("unchecked")
        List<String> shopIds = (List<String>) paraMap.get("shopIds");
        if (null == shopIds) {
            return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);
        }
        for (String shopId : shopIds) {
            this.baseMapper.delete(new LambdaQueryWrapper<UserFavoritesShopEntity>()
                    .eq(UserFavoritesShopEntity::getShopId,shopId)
                    .eq(UserFavoritesShopEntity::getUserId,userId));


            Map<String, String> delMap = new HashMap<String, String>();
            delMap.put("shopId", shopId);
            delMap.put("type", "2");
            businessServiceClient.updateShopCollect(delMap);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult delFavoritesByShopId(Integer shopId) {
        int count = this.baseMapper.delete(new LambdaQueryWrapper<UserFavoritesShopEntity>()
                .eq(UserFavoritesShopEntity::getShopId, shopId));
        if (count > 0) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.DELETE_ERROR.getCode(), BizCodeEnume.DELETE_ERROR.getMsg());
    }
}
